import { FunctionComponent, useEffect, useState, useImperativeHandle, forwardRef } from "react";

export interface ITimeAccountProps {
    /** 格式化时间 */
    format?: string;
    /** 回调 */
    onTimeChange?: (time: number) => void;
}

export interface ITimeAccountExpose {
    stopTime?: () => void;
}

let timer: any = null;

/** 计时器 */
const TimeAccount = forwardRef<any, ITimeAccountProps>(({ format = "HH:MM:SS", onTimeChange }, ref) => {

    const [timeStamp, setTimeStamp] = useState<number>(0);
    const [isStop, setIsStop] = useState<boolean>(false);

    /** 格式化倒计时 */
    const formatTime = (formatStr: string) => {
        let hours = 0, minutes = 0, seconds = 0;
        seconds = timeStamp % 60;
        minutes = ((timeStamp - seconds) / 60) % 60;
        hours = Math.floor((timeStamp - minutes * 60 - seconds) / 3600);
        formatStr = formatStr.replaceAll("HH", String(hours).padStart(2, '0'))
        formatStr = formatStr.replaceAll("MM", String(minutes).padStart(2, '0'))
        formatStr = formatStr.replaceAll("SS", String(seconds).padStart(2, '0'))
        return formatStr;
    }

    const stopTime = () => {
        setIsStop(true);
    }

    useEffect(() => {
        if (isStop) {
            clearTimeout(timer);
            timer = false;
            return;
        }
        onTimeChange?.(timeStamp);
        timer = setTimeout(() => {
            setTimeStamp(timeStamp + 1)
        }, 1000);
    }, [timeStamp])

    useImperativeHandle(ref, () => ({
        stopTime
    }))

    return (
        <span>{formatTime(format)}</span>
    )
})

export default TimeAccount;